<?php

namespace App\Lib\Upload;

use App\Lib\AliyunSdk\AliVod;

class Base
{

    public $type = "";

    public $size = "";

    public function __construct($request,$type = null)
    {
        $this->request = $request;
        if(empty($type)){
            $files = $this->request->getSwooleRequest()->files;
            $types = array_keys($files);
            $this->type = $types[0];
        }else{
            $this->type = $type;
        }
    }

    public function upload($isRemote = 1)
    {
        if($this->type != $this->fileType){
            return false;
        }
        
        $videos = $this->request->getUploadedFile($this->type);
        // 获取文件大小
        $this->size = $videos->getSize();
        $this->checkSize();
        if($isRemote == 1){
            // 上传阿里云
            $tmpName = $videos->getTempName();
            $file = $this->uploadRemoteFile($tmpName);
            return $file->PlayInfoList->PlayInfo[0]->PlayURL;
        }
        $fileName = $videos->getClientFileName();

        $this->clientMediaType = $videos->getClientMediaType();
        $this->checkMediaType();

        $file = $this->getFile($fileName);
        $videos->moveTo($file);
        return $this->file;
    }

    // 获取视频名称
    public function getFile($fileName)
    {
        $pathinfo = pathinfo($fileName);
        $extension = $pathinfo['extension'];
        $dirname = "/".$this->type."/".date('Y')."/".date('n');
        $dir = EASYSWOOLE_ROOT . "/webroot" . $dirname;
        if(!is_dir($dir)){
            mkdir($dir,0077,true);
        }
        $basename = '/'.md5(time()).'.'.$extension;
        $this->file = $dirname.$basename;
        return $dir.$basename;
    }

    // 判断视频大小
    public function checkSize()
    {
        if(empty($this->size)){
            return false;
        }
        
        if($this->size > $this->maxSize){
            return false;
        }
    }


    // 判断视频格式
    public function checkMediaType()
    {
        $clientMediaType = explode('/',$this->clientMediaType)[1];
        if(empty($clientMediaType)){
            throw new \Exception("上传{$this->type}文件不合法");
        }
        if(!in_array($clientMediaType,$this->fileExtTypes)){
            throw new \Exception("上传{$this->type}文件不合法");
        }
        return true;
    }

    // 上传文件到远程
    public function uploadRemoteFile($file)
    {
        $aliVod = new AliVod();
        $result = $aliVod->createUploadVideo('测试视频','1.mp4');
        $videoId = $result->VideoId;
        $uploadAuth = json_decode(base64_decode($result->UploadAuth),true);
        $uploadAddress = json_decode(base64_decode($result->UploadAddress),true);
        $aliVod->initOssClient($uploadAuth, $uploadAddress);
        $result = $aliVod->uploadLocalFile($uploadAddress,$file);
        $result = $aliVod->getPlayInfo($videoId);
        return $result;
    }


}